package com.shiro;

import com.alibaba.fastjson.JSONObject;
import com.bean.ResponseBean;
import com.pojo.Admin;
import com.pojo.Log;
import com.service.AdminService;
import com.service.LogService;
import com.service.PermissionService;
import com.util.IPUtil;
import com.util.JwtUtil;
import com.util.StringUtil;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class SessionFilter extends BasicHttpAuthenticationFilter {

    private ApplicationContext ctx ;

    public SessionFilter(ApplicationContext ctx){
        this.ctx = ctx ;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse response, Object mappedValue) {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String url = ((HttpServletRequest) request).getRequestURI();
            String username = null ;

            String token;
            try {
                token = request.getHeader("token");
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            if (StringUtil.isNull(token)){
                return false;
            }
            String uid = JwtUtil.getUsername(token);

            AdminService adminService = ctx.getBean(AdminService.class);
            Admin userinfo = adminService.getById(uid);
            if (userinfo==null){
                return false;
            }
            LogService logService = ctx.getBean(LogService.class) ;
            PermissionService permissionService = ctx.getBean(PermissionService.class) ;

            if(userinfo==null){
                return false;
            }
            username = userinfo.getUsername();

            UsernameAuth usernameAuth = new UsernameAuth(username);
            getSubject(request, response).login(usernameAuth);  //登录
            try{
                getSubject(request, response).checkPermission(url);
            }catch(AuthorizationException e){
                return false ;
            }//权限

            String name = permissionService.getPermissionByUrl(url) ;

            //定时器不写日志
            if (url.trim().contains("verifyLogin")){
                return true;
            }

            String ipAddr = IPUtil.getIpAddr(request);

            Log log = new Log() ;
            log.setCaozuo(name);
            log.setIp(ipAddr);
            log.setCaozuoTime(new Date());
            log.setUser(username);
            log.setUrl(url);
            try {
                logService.save(log) ;
            }catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        //httpServletResponse.setStatus(401);
        ResponseBean result = new ResponseBean();
        result.setCode(401);
        result.setMsg("拒绝访问");
        result.setCount(0L);
        result.setData(null);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(JSONObject.toJSONString(result));
        return false;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.addHeader("Access-Control-Allow-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        httpServletResponse.addHeader("Access-Control-Expose-Headers", "token");

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request,response);
    }
}
